#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_ag_util-linux_chrt_004.py
@Time:      2022/06/20 11:12:50
@Author:    zhangtaibo
@Version:   1.0
@Contact:   zhangtaibo.ztb@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    zhangtaibo
"""

import os
from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_ag_util-linux_chrt_fun_004.yaml for details

    :avocado: tags=fix,P1,noarch,local,ag
    """
    PARAM_DIC = {"pkg_name": "util-linux"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        # create a test pid
        os.system('sleep 10000 &')
        ret_c, self.test_pid = self.cmd('ps aux | grep "sleep 10000" | grep -v grep| awk "{print \$2}"')
    
    def test(self):
        chrt_policy_op_dic = {
            "--deadline": "SCHED_DEADLINE",
            "--rr": "SCHED_RR",
            "--batch": "SCHED_BATCH",
            "--fifo": "SCHED_FIFO",
            "--idle": "SCHED_IDLE",
            "--other": "SCHED_OTHER"
        }
        
        for policy_op in chrt_policy_op_dic.keys():
            chrt_priority = "0"
            if policy_op == "--rr" or policy_op == "--fifo":
                chrt_priority = "1"
            if policy_op == "--deadline":
                cmdline = "chrt -T 10000 -P 100000 -D 100000 %s --pid %s %s" % \
                (policy_op, chrt_priority, self.test_pid)
            else:
                cmdline = "chrt %s --pid %s %s" % (policy_op, chrt_priority, self.test_pid)
            check_msg = "pid %s's current scheduling policy: %s" % (self.test_pid, chrt_policy_op_dic[policy_op])
            self.cmd(cmdline)
            ret_c, ret_o = self.cmd("chrt -p %s" % self.test_pid)
            self.assertTrue(check_msg in ret_o, 'check output error.')
        
        invalid_pid_dic = {
            "abc": "chrt: invalid PID argument: 'abc'",
            "0": "chrt: failed to execute 0: No such file or directory",
            "2147483647": "chrt: failed to set pid 2147483647's policy: No such process",
            "2147483648": "chrt: invalid PID argument: '2147483648': Numerical result out of range",
            " ": "chrt: invalid PID argument: '--pid'"
        }
        for invalid_pid in invalid_pid_dic.keys():
            chrt_priority = "0"
            if invalid_pid == " ":
                chrt_priority = ""
            cmdline = "chrt --other --pid %s %s" % (chrt_priority, invalid_pid)
            ret_c, ret_o = self.cmd(cmdline, ignore_status=True)
            self.assertTrue(ret_c is not 0, 'return code should not be 0.')
            self.assertTrue(invalid_pid_dic[invalid_pid] in ret_o, 'check output error.')
    
    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd('ps aux | grep "sleep 10000" | grep -v grep| awk "{print \$2}" | xargs kill -9')
